package net.mikoo.seals.boss.web.directive;

import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import net.mikoo.seals.boss.biz.manager.LinkageManager;
import net.mikoo.seals.boss.model.Linkage;

public class LinkageDirective implements TemplateDirectiveModel {

	private Logger logger = Logger.getLogger(LinkageDirective.class);
	
	@Autowired
	private LinkageManager  linkageManager;

	@SuppressWarnings("rawtypes")
	@Override
	public void execute(Environment env, Map params, TemplateModel[] model, TemplateDirectiveBody body) throws TemplateException, IOException {
		try {

			String type = params.get("type").toString();

			String key = params.get("key").toString();
			
			Linkage  linkage = linkageManager.getLinkage(type, key);
			if(linkage == null) {
				linkage = new Linkage();
			}
			

			@SuppressWarnings("unchecked")
			Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
			paramWrap.put("linkage", DEFAULT_WRAPPER.wrap(linkage));

			Map<String, TemplateModel> origMap = DirectiveUtil.addParamsToVariable(env, paramWrap);

			body.render(env.getOut());

			DirectiveUtil.removeParamsFromVariable(env, paramWrap, origMap);

		} catch (Exception e) {
			logger.error("", e);
		}
	}

}